const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');
const { validate } = require('../../../lib/validation');
const Joi = require('joi');

// 产品创建验证Schema
const createProductSchema = Joi.object({
  name: Joi.string().max(100).required(),
  code: Joi.string().max(50).required(),
  category_id: Joi.number().integer().positive(),
  vendor: Joi.string().max(100),
  version: Joi.string().max(50),
  description: Joi.string(),
  launch_date: Joi.date(),
  support_level: Joi.string().valid('full', 'maintenance', 'limited', 'none').default('full'),
  business_value: Joi.string().valid('critical', 'high', 'medium', 'low').default('medium'),
  user_count: Joi.number().integer().min(0).default(0),
  documentation_url: Joi.string().uri(),
  repository_url: Joi.string().uri(),
  end_of_life_date: Joi.date()
});

async function handler(req, res) {
  try {
    switch (req.method) {
      case 'GET':
        return await getProducts(req, res);
      case 'POST':
        return await createProduct(req, res);
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('产品API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

async function getProducts(req, res) {
  try {
    // Ultra simple query for debugging
    const products = await query('SELECT * FROM products LIMIT 10');
    
    res.status(200).json({
      success: true,
      data: products
    });
  } catch (error) {
    console.error('Products query error:', error);
    res.status(500).json({
      success: false,
      message: 'Database query failed',
      error: error.message
    });
  }
}

async function createProduct(req, res) {
  const validation = validate(createProductSchema, req.body);
  if (!validation.isValid) {
    return res.status(400).json({
      success: false,
      message: '请求数据验证失败',
      errors: validation.errors
    });
  }

  const {
    name,
    code,
    category_id,
    vendor,
    version,
    description,
    launch_date,
    support_level,
    business_value,
    user_count,
    documentation_url,
    repository_url,
    end_of_life_date
  } = validation.data;

  const result = await query(`
    INSERT INTO products (
      name, code, category_id, vendor, version, description, launch_date,
      support_level, business_value, user_count, documentation_url, 
      repository_url, end_of_life_date
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `, [
    name, code, category_id, vendor, version, description, launch_date,
    support_level, business_value, user_count, documentation_url,
    repository_url, end_of_life_date
  ]);

  const newProduct = await query(`
    SELECT p.*, pc.name as category_name
    FROM products p
    LEFT JOIN product_categories pc ON p.category_id = pc.id
    WHERE p.id = ?
  `, [result.insertId]);

  res.status(201).json({
    success: true,
    message: '产品创建成功',
    data: newProduct[0]
  });
}

export default authenticateToken(handler);